package com.vpx.server.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 获取当前时间周数，及根据周数获取周的起止时间
 */
public class DateWorkUtil {
    public static void dateWeek(Date d) {
        Calendar c = Calendar.getInstance();
        // 设置每周的开始日期
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(d);
        c.setMinimalDaysInFirstWeek(7);
        String getCurrentTime=new SimpleDateFormat("yyyy-MM-dd ").format(c.getTime());
        System.out.println(getCurrentTime);//年-月-日
        String getCurrent1=new SimpleDateFormat("yyyy-MM ").format(c.getTime());
        System.out.println(getCurrent1);//年-月
        System.out.println("当前时间 年-月-日：" + new SimpleDateFormat("yyyy-MM-dd ").format(c.getTime()));
        System.out.println("当前时间 年-月-日 时：分：秒：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime()));
        System.out.println("当前时间的年份：" + c.get(Calendar.YEAR));//获取当前年
        System.out.println("当前时间的月份：" + (c.get(Calendar.MONTH) + 1));
        System.out.println("当前时间的年周数：" + c.get(Calendar.WEEK_OF_YEAR));
        //判断周数如果为52，月份不为12月，则代表跨年周，所属年份需减一
        if(c.get(Calendar.WEEK_OF_YEAR) == 52 && (c.get(Calendar.MONTH) + 1) < 12){
            System.out.println("当前时间周数所属年份：" + (c.get(Calendar.YEAR) -1 ));
        }else {
            System.out.println("当前时间周数所属年份：" + c.get(Calendar.YEAR));
        }
    }

    /**
     * 根据具体年份周数获取日期范围
     * @param year
     * @param week
     * @return
     */
    public static List<String> getWeekDays(int year, int week) {
        List<String> list = new ArrayList<>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal=Calendar.getInstance();
        // 设置每周的开始日期
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setMinimalDaysInFirstWeek(7);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, week);
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        String beginDate = sdf.format(cal.getTime());

        cal.add(Calendar.DAY_OF_WEEK, 6);
        String endDate = sdf.format(cal.getTime());
        list.add(beginDate);
        list.add(endDate);
        return list;
    }

    public static void main(String[] s) {
        getWeekDays(2023,1);
    }
}
